// pages/welfareMall/cart/index.js
//获取应用实例
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //服务器图片的路径片段
    imgUrl:app.globalData.iconImgUrl,
    StatusBar: app.globalData.StatusBar,   //状态栏高度
    CustomBar: app.globalData.CustomBar,  //头部nav高度
    backIcon: true,   // 返回按钮是否显示
    title: "购物车",  //页面标题
    backImg: app.globalData.iconImgUrl+"arrow-left.svg",
    hasData: false,
    cartList: '',
    selCount: 0,
    totalPrice: 0,
    totalHonor: 0,
    currentPage: 1,
    pageSize: 6,
    shopcartList: [],
    checkAll: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getList()
  },
  getList() {
    const data = {
      "userCode": wx.getStorageSync('userCode'),
      "currentPage": this.data.currentPage,
      "pageSize": this.data.pageSize
    }
    const that = this
    wx.request({
      url: app.globalData.baseUrl + 'shopcard/getShopCartList.do',
      data: data,
      method: 'post',
      success(res) {
        console.log('购物车', res)
        const list = that.pushData(res.data.productList)
        that.setData({
          cartList: list,
          hasData: true,
          totalPage: res.data.pageInfo.totalPage
        })
      }
    })
  },
  pushData(array) {
    let cartList;
    if (this.data.cartList) {
      cartList = this.data.cartList
    } else {
      cartList = []
    }

    array.forEach(item => {
      cartList.push(item)
    })
    return cartList
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  handleChange({ detail }) {
    console.log(detail)
    var index = detail.e.target.dataset.itemindex,
          type = detail.type;
    var item = "cartList[" + index + "].num",
          totalPrice = this.data.totalPrice,
          totalHonor = this.data.totalHonor,
          price = parseInt(this.data.cartList[index].goodsPrice),
          selCount = this.data.selCount,
          seled = this.data.cartList[index].seled;
    // var price = "cartList[" + index + "].price",
    //       historyPrice = this.data.cartList[index].price;
    var honor = "cartList[" + index + "].honor",
          historyHonor = this.data.cartList[index].ydPrice,
          id = this.data.cartList[index].shopcardId,
          num = this.data.cartList[index].num
    
    // if (type == "plus" && seled){
    if (type == "plus") {
      this.setData({
        [item]: detail.value,
        totalPrice: totalPrice + price,
        totalHonor: totalHonor + historyHonor,
        selCount: selCount+1
      })
      this.addGoodsNum(id, num + 1)
    // } else if (type == "minus" && seled){
    } else if (type == "minus") {
      this.setData({
        [item]: detail.value,
        totalPrice: totalPrice - price
      })
      this.addGoodsNum(id, num + 1)
    }
    
  },
  addGoodsNum(id, num) {
    const data = {
      "userCode": wx.getStorageSync('userCode'),
      "num": num,
      "shopcartId": id
    }
    // console.log("参数", data)
    wx.request({
      url: app.globalData.baseUrl + 'shopcard/changeShopcartNum.do',
      data: data,
      method: 'post',
      success(res) {
        console.log('增加商品数量', res)
      }
    })
  },
  seledItem(e) {
    var index = e.currentTarget.dataset.index,
      id = e.currentTarget.dataset.id;
    var item = "cartList[" + index + "].seled";
    var seled = this.data.cartList[index].seled,
      number = this.data.cartList[index].num,
      cash = this.data.cartList[index].goodsPrice,
      honor = this.data.cartList[index].ydPrice,
      selCount = this.data.selCount,
      totalPrice = this.data.totalPrice,
      totalHonor = this.data.totalHonor,
      length = this.data.cartList.length,
      shopcartList = this.data.shopcartList;

    if (seled) {
      // console.log(id)
      console.log('id', id , shopcartList)
      // shopcartList.indexOf('' + id);
      for (var i = 0; i < shopcartList.length; i++) {
        if (shopcartList[i] === id) {
          shopcartList.splice(i, 1);
        }
      }
      // console.log(shopcartList)
      this.setData({
        [item]: false,
        totalPrice: totalPrice - cash * number,
        totalHonor: totalHonor - honor * number,
        selCount: selCount - number,
        checkAll: false,
        shopcartList: shopcartList
      })
    } else {
      shopcartList.push(id)
      this.setData({
        [item]: true,
        totalPrice: totalPrice + cash * number,
        totalHonor: totalHonor + honor * number,
        selCount: selCount + number,
        shopcartList: shopcartList
      })
      selCount = this.data.selCount;
      let goodCount = 0, that = this;
      for(var i = 0; i < length; i++) {
        goodCount += that.data.cartList[i].num;
      }
      // console.log(selCount, goodCount)
      if (selCount === goodCount) {
        this.setData({
          checkAll: true
        })
      }
    }
    console.log(shopcartList)
  },
  selAll() {
    var that = this,
          length = this.data.cartList.length,
          checkAll = this.data.checkAll,
          checkVal,
          selCount = 0,
          totalPrice = 0,
          totalHonor = 0,
          shopcartList = [];

    if (checkAll) {
      checkVal = false
    }else{
      checkVal = true
      that.data.cartList.forEach(item => {
        // console.log(item)
        shopcartList.push(item.shopcardId)
      })
    }
    for(var i = 0; i < length; i++){
      let item = "cartList[" + i + "].seled"
      if (!checkAll) {
        selCount += that.data.cartList[i].num
        totalPrice = that.data.cartList[i].goodsPrice * that.data.cartList[i].num
        totalHonor = that.data.cartList[i].ydPrice * that.data.cartList[i].num
      }      
      that.setData({
        [item]: checkVal
      })
    }
    that.setData({
      checkAll: checkVal,
      selCount: selCount,
      totalPrice: totalPrice,
      totalHonor: totalHonor,
      shopcartList: shopcartList
    })
  },
  gotoPay() {
    // console.log(this.data.shopcartList)
    if (this.data.shopcartList.length > 0){
      wx.navigateTo({
        url: "./order/index?type=1&idArr=" + this.data.shopcartList.join(',')
      })
    }else{
      wx.showToast({
        title: '请选择商品',
        image: '/assets/images/icon/error.png'
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      shopcartList: []
    })
    this.resetList()
  },
  resetList() {
    var data = this.data.cartList
    for(var i = 0; i<data.length; i++) {
      data[i].seled = false
    }
    this.setData({
      cartList: data,
      selCount: 0,
      totalPrice: 0,
      totalHonor: 0,
      checkAll: false
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const currentPage = this.data.currentPage
    const totalPage = this.data.totalPage
    if(currentPage < totalPage) {
      this.setData({
        currentPage: currentPage + 1
      })
      this.getList()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})